<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title></title>
  </head>
  <body>
    <div id="message"></div>
    <script src="./websso/js/axios.min.js"></script>
    <script src="../config.js"></script>
    <script>
      axios.interceptors.response.use(
        function(response) {
          if (response.status === 200) {
            return response.data;
          } else {
            return Promise.reject(error);
          }
        },
        function(error) {
          return Promise.reject(error);
        }
      );

      const obj = {
        messageNode: document.getElementById("message"),
        origin: config.redirectHost, // 当前域名主页
        apiHost: config.apiHost, // 接口请求域
        currentUrl: new URL(location.href),
        api: {
          getToken: "/login/websso",
        },
      };

      /**
       * 设置错误信息内容
       * @param {string} val 内容
       * @return {void}
       */
      function setMessage(val) {
        obj.messageNode.innerText = val ? val : "";
      }

      /**
       * 初始化页面
       * @param {void}
       * @return {void}
       */
      function init() {
        const code = obj.currentUrl.searchParams.get("code");
        const return_uri = decodeURIComponent(
          obj.currentUrl.searchParams.get("return_uri")
        );

        if (!code) {
          setMessage("缺少参数");
          return;
        }

        axios
          .get(obj.apiHost + obj.api.getToken, {
            params: { code: code },
          })
          .then((res) => {
            if (res && res.errcode === 0) {
              localStorage.setItem("token", res.access_token);
              localStorage.setItem("refresh_token", res.refresh_token);
              localStorage.setItem(
                "expireTime",
                parseInt(`${res.expiration / 1000}`).toString()
              );
              location.replace(return_uri ? return_uri : obj.origin);
            } else {
              setMessage("登录失败");
            }
          })
          .catch((err) => {
            setMessage("请求异常");
            console.log(err);
          });
      }

      init();
    </script>
  </body>
</html>
